/*
 * @Author: liutongchao 1923236391@qq.com
 * @Date: 2023-05-31 13:44:24
 * @LastEditors: liutongchao 1923236391@qq.com
 * @LastEditTime: 2024-07-31 15:23:18
 * @FilePath: \greenbeeadmin\controllers\admin\service\userService.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package service

import (
	"fmt"
	greenbeeUtils "greenbeeadmin/controllers/greenbee/utils"
	"greenbeeadmin/models"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

/**
 * @description: 验证数据 service
 * @return {*}
 */
type VerificationService struct {
	AdminBaseService
}

/**
 * @description: 添加
 * @param {models.Verificationting} data
 * @return {*}
 */
func (s *VerificationService) Add(data models.Verification) int64 {
	o := orm.NewOrm()
	id, err := o.Insert(&data)
	if err == nil {
		//fmt.Println(id)
	}
	return id
}

/**
 * @description: 编辑
 * @param {models.Verification} data
 * @return {*}
 */
func (s *VerificationService) Edit(data models.Verification, uid int, field []string) int64 {
	o := orm.NewOrm()
	user := models.Verification{Id: uid}
	if o.Read(&user, "Id") == nil {
		data.Id = uid
		if num, err := o.Update(&data, field...); err == nil {
			fmt.Println(num)
			return num
		}
	}
	return 0
}

/**
 * @description: 获取数据
 * @param {models.Verification} data
 * @param {[]string} field
 * @return {*}
 */
func (s *VerificationService) GetData(data models.Verification, field []string) (models.Verification, error) {
	o := orm.NewOrm()
	err := o.Read(&data, field...)
	if err == orm.ErrNoRows {
		fmt.Println("查询不到")
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键")
	}
	return data, err
}

/**
 * @description: 根据条件获取数据
 * @param {models.CallbackAction} data
 * @param {[]string} field
 * @return {*}
 */
func (s *VerificationService) GetDataByWhere(table models.Verification, where string, field []string) ([]models.Verification, error) {
	table_name := table.GetTableName()
	var datas []models.Verification
	// 获取 QueryBuilder 对象. 需要指定数据库驱动参数。
	// 第二个返回值是错误对象，在这里略过
	qb, _ := orm.NewQueryBuilder("mysql")
	// 构建查询对象
	if len(field) == 0 {
		field = append(field, "*")
	}
	qb.Select(field...).
		From(table_name).
		Where(where).
		OrderBy("id").Desc()
	// 导出 SQL 语句
	sql := qb.String()
	// 执行 SQL 语句
	o := orm.NewOrm()
	_, err := o.Raw(sql).QueryRows(&datas)
	return datas, err
}

/**
 * @description: 创建验证数据
 * @param {*} verify_type 验证类型 : email , duanxin
 * @param {string} name 验证信息 : 邮箱，手机号，等
 * @param {int64} expiration_time 验证过期时间 单位秒 ，默认：0 十分钟
 * @return {*}
 */
func (s *VerificationService) CreateVerificationData(verify_type, name string, expiration_time int64) (string, bool) {
	//查询验证数据是否过期
	timestamp := time.Now().Unix() //获取当前时间戳
	var search_data models.Verification
	find_time := greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", (timestamp + 120))
	where := "status = 0 and name='" + name + "' and verify_type='" + verify_type + "' and expiration_time > '" + find_time + "'"
	field := []string{"*"}

	find_data, err := s.GetDataByWhere(search_data, where, field)
	//未过期，直接返回数据
	if err == nil && len(find_data) > 0 {
		return find_data[0].Verify_code, true
	}

	rand_code := greenbeeUtils.CreateRandomString(6)
	//保存验证码到数据库
	var add_data models.Verification
	add_data.Verify_type = verify_type
	add_data.Name = name
	add_data.Verify_code = rand_code
	add_data.Verify_time = "1970-01-01 00:00:00"
	add_data.Created_at = greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", timestamp)

	//过期时间默认 10分钟
	expiration_timestamp := time.Now().Unix() + 600
	if expiration_time > 0 {

		expiration_timestamp = time.Now().Unix() + expiration_time

	}

	add_data.Expiration_time = greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", expiration_timestamp)
	add_res := s.Add(add_data)
	if add_res <= 0 {
		return "", false
	}
	return rand_code, true
}

/**
 * @description: 获取验证数据list
 * @param {*} verify_type 验证类型 : email , duanxin
 * @param {string} name 验证信息 : 邮箱，手机号，等
 * @param {int64} start_time 查询的起始时间,默认 0 当天0点
 * @return {*}
 */
func (s *VerificationService) GetVerificationDatas(verify_type, name string, start_time int64) []models.Verification {
	var return_data []models.Verification

	var search_data models.Verification
	find_time := greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", start_time)
	if start_time == 0 {
		timestamp := time.Now().Unix() //获取当前时间戳
		//当天的开始时间
		find_time = greenbeeUtils.GetTodayFmtStr("2006-01-02", timestamp) + " 00:00:00"
	}
	where := "name='" + name + "' and verify_type='" + verify_type + "' and created_at >= '" + find_time + "'"
	field := []string{"*"}

	return_data, err := s.GetDataByWhere(search_data, where, field)

	if err == nil && len(return_data) > 0 {
		return return_data
	}
	return return_data
}

/**
 * @description: 验证数据
 * @param {*} verify_type 验证类型 : email , duanxin
 * @param {string} name 验证信息 : 邮箱，手机号，等
 * @param {string} verify_code 验证码
 * @return {*}
 */
func (s *VerificationService) ToVerificationData(verify_type, name, verify_code string) bool {
	//查询验证数据是否过期
	timestamp := time.Now().Unix() //获取当前时间戳
	var search_data models.Verification
	find_time := greenbeeUtils.GetTodayFmtStr("2006-01-02 15:04:05", timestamp)
	where := "status = 0 and name='" + name + "' and verify_type='" + verify_type + "' and expiration_time > '" + find_time + "' and verify_code='" + verify_code + "'"
	field := []string{"*"}

	find_data, err := s.GetDataByWhere(search_data, where, field)
	//存在数据
	if err == nil && len(find_data) > 0 {
		id := find_data[0].Id
		//更新状态
		var update_data models.Verification
		update_data.Status = 1
		update_data.Verify_time = find_time
		field := []string{"Status", "Verify_time"}
		s.Edit(update_data, id, field)
		return true
	}

	return false
}
